# -*- coding: utf-8 -*-
import os
import json
import logging
from typing import List, Dict, Optional
import requests
from youtube_transcript_api.proxies import WebshareProxyConfig
# 使用youtube-transcript-api库
from youtube_transcript_api import YouTubeTranscriptApi

class VideoSubtitleTranslator:
    def __init__(self, output_dir: str = "output/subtitles", proxy_config: WebshareProxyConfig = None):
        self.output_dir = output_dir
        self.logger = logging.getLogger(__name__)
        self.proxy_config = proxy_config  # 保存代理配置
        os.makedirs(self.output_dir, exist_ok=True)
        
        # 设置代理（如果需要）
        self.proxy = None
        if os.getenv("HTTP_PROXY") or os.getenv("HTTPS_PROXY"):
            self.proxy = {
                'http': os.getenv("HTTP_PROXY", ""),
                'https': os.getenv("HTTPS_PROXY", "")
            }

    def get_transcript(self, video_id: str, languages: List[str] = None) -> Optional[List[Dict]]:
        """
        获取视频字幕（使用youtube-transcript-api库）
        
        :param video_id: YouTube视频ID
        :param languages: 优先语言列表
        :return: 字幕列表或None
        """
        if languages is None:
            languages = ['en', 'zh-CN', 'zh', 'ja', 'ko', 'es', 'fr', 'de']
            
        try:
            # 尝试使用代理配置
            if self.proxy_config:
                self.logger.info(f"🛡️ 使用Webshare代理获取字幕")
                transcript_data = YouTubeTranscriptApi(proxy_config=self.proxy_config).fetch(video_id, languages=languages)
            else:
                # 直接获取字幕
                transcript_data = YouTubeTranscriptApi().fetch(video_id, languages=languages)
            
            # 转换数据格式
            if transcript_data:
                # 将FetchedTranscriptSnippet对象转换为字典列表
                result = []
                for item in transcript_data:
                    result.append({
                        "start": item.start,
                        "duration": item.duration,
                        "text": item.text
                    })
                    
                self.logger.info(f"成功获取到 {len(result)} 条字幕")
                return result
            else:
                self.logger.warning("未找到任何可用字幕")
                return None
            
        except Exception as e:
            self.logger.error(f"获取字幕时发生错误: {str(e)}")
            return None

    def save_transcript(self, transcript: List[Dict], video_id: str, format: str = "srt") -> str:
        """
        保存字幕到文件
        
        :param transcript: 字幕数据
        :param video_id: 视频ID
        :param format: 输出格式 (srt, json, txt)
        :return: 文件路径
        """
        if format == "json":
            filename = os.path.join(self.output_dir, f"{video_id}.json")
            with open(filename, "w", encoding="utf-8") as f:
                json.dump(transcript, f, ensure_ascii=False, indent=2)
        elif format == "srt":
            filename = os.path.join(self.output_dir, f"{video_id}.srt")
            srt_content = self._convert_to_srt(transcript)
            with open(filename, "w", encoding="utf-8") as f:
                f.write(srt_content)
        else:  # txt
            filename = os.path.join(self.output_dir, f"{video_id}.txt")
            txt_content = "\n".join([item["text"] for item in transcript])
            with open(filename, "w", encoding="utf-8") as f:
                f.write(txt_content)
                
        self.logger.info(f"字幕已保存到: {filename}")
        return filename

    def _convert_to_srt(self, transcript: List[Dict]) -> str:
        """
        将字幕转换为SRT格式
        
        :param transcript: 字幕数据
        :return: SRT格式字符串
        """
        srt_lines = []
        for i, entry in enumerate(transcript, 1):
            start_time = self._seconds_to_srt_time(entry["start"])
            duration = entry.get("duration", 5.0)
            end_time = self._seconds_to_srt_time(entry["start"] + duration)
            
            srt_lines.append(str(i))
            srt_lines.append(f"{start_time} --> {end_time}")
            srt_lines.append(entry["text"].strip())
            srt_lines.append("")  # 空行分隔
            
        return "\n".join(srt_lines)

    def _seconds_to_srt_time(self, seconds: float) -> str:
        """
        将秒数转换为SRT时间格式 (HH:MM:SS,mmm)
        
        :param seconds: 秒数
        :return: SRT时间格式字符串
        """
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        millisecs = int((seconds % 1) * 1000)
        return f"{hours:02d}:{minutes:02d}:{secs:02d},{millisecs:03d}"

    def translate_single_video(self, video_id: str, format: str = "srt"):
        """
        翻译单个视频字幕
        
        :param video_id: YouTube视频ID
        :param format: 输出格式
        """
        self.logger.info(f"正在处理视频: {video_id}")
        
        # 获取字幕
        transcript = self.get_transcript(video_id)
        if not transcript:
            self.logger.warning(f"跳过视频 {video_id}，无可用字幕")
            return
            
        # 保存字幕
        filename = self.save_transcript(transcript, video_id, format)
        self.logger.info(f"✅ 视频 {video_id} 字幕处理完成: {filename}")

    def batch_translate_videos(self, video_ids: List[str], format: str = "srt"):
        """
        批量翻译视频字幕
        
        :param video_ids: YouTube视频ID列表
        :param format: 输出格式
        """
        self.logger.info(f"开始批量处理 {len(video_ids)} 个视频")
        
        for video_id in video_ids:
            try:
                self.translate_single_video(video_id, format)
            except Exception as e:
                self.logger.error(f"处理视频 {video_id} 时出错: {str(e)}")

    def translate_all_videos_in_db(self, db_manager, format: str = "srt"):
        """
        翻译数据库中所有视频的字幕
        
        :param db_manager: 数据库管理器
        :param format: 输出格式
        """
        from sqlalchemy import text
        
        session = db_manager.Session()
        try:
            # 获取所有YouTube视频ID
            result = session.execute(
                text("SELECT video_id FROM d_video_sources WHERE platform = 'youtube' AND video_id IS NOT NULL")
            )
            video_ids = [row[0] for row in result]
            
            self.logger.info(f"从数据库获取到 {len(video_ids)} 个视频")
            self.batch_translate_videos(video_ids, format)
            
        except Exception as e:
            self.logger.error(f"从数据库获取视频列表时出错: {str(e)}")
        finally:
            session.close()